﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;

namespace AirLib
{
    public class ReverseConnectionHandler
    {

        #region Fields

        private Guid _sessionGuid;
        private string _appleTvIpAddress;
        private string _eventType;

        #endregion Fields

        #region Delegates

        public delegate byte[] EventFiredDelegate(string eventMessage);
        public event EventFiredDelegate EventRaised;

        #endregion Delegates

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="ReverseConnectionHandler"/> class.
        /// </summary>
        /// <param name="ipAddress">The ip address.</param>
        public ReverseConnectionHandler(string ipAddress, string eventType, Guid sessionGuid)
        {
            _appleTvIpAddress = ipAddress;
            _eventType = eventType;
            _sessionGuid = sessionGuid;

            Thread eventThread = new Thread(new ThreadStart(StartRecievingEvents));
            eventThread.Start();
        }

        #endregion Constructor

        #region Methods

        /// <summary>
        /// Starts recieving events from the AppleTV.
        /// </summary>
        private void StartRecievingEvents()
        {
            //This is supposed to be a "reverse" connection and while the connection appears to be set up,
            //I have not noted any events firing.  It is quite possible that this is simply not done correctly.

            string request = "POST /reverse HTTP/1.1\n" +
                         "Upgrade: PTTH/1.0\n" +
                         "Connection: Upgrade\n" +
                         "Content-Length: 0\n" +
                         "User-Agent: MediaControl/1.0\n" +
                         "X-Apple-Purpose: " + _eventType + "\n" +
                         "X-Apple-Session-ID: " + _sessionGuid.ToString() + "\n\n";


            using (TcpClient tcpClient = new TcpClient(_appleTvIpAddress, AppleTv.AppleTvPort))
            {

                //get the client stream to read data from.
                NetworkStream clientStream = tcpClient.GetStream();

                byte[] byData = System.Text.Encoding.ASCII.GetBytes(request);
                clientStream.Write(byData, 0, byData.Length);

                byte[] buffer = new byte[10000];

                while (true)
                {
                    int recieved = clientStream.Read(buffer, 0, buffer.Length);
                    string str = Encoding.ASCII.GetString(buffer, 0, recieved);
                    if (EventRaised != null)
                    {
                        byData = EventRaised(str);
                        if (byData != null)
                        {
                            clientStream.Write(byData, 0, byData.Length);
                        }
                    }
                    Thread.Sleep(100);
                }

            }
        }

        #endregion Methods


    }
}
